const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('📊 获取用户登录日志')
  
  try {
    const { OPENID } = cloud.getWXContext()
    const { 
      page = 1, 
      pageSize = 20,
      startDate = null,
      endDate = null,
      loginType = null
    } = event
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    // 构建查询条件
    const whereCondition = { openid: OPENID }
    
    // 添加时间范围过滤
    if (startDate || endDate) {
      whereCondition.loginTime = {}
      if (startDate) {
        whereCondition.loginTime[db.command.gte] = new Date(startDate)
      }
      if (endDate) {
        whereCondition.loginTime[db.command.lte] = new Date(endDate)
      }
    }
    
    // 添加登录类型过滤
    if (loginType) {
      whereCondition.loginType = loginType
    }
    
    console.log('🔍 查询条件:', whereCondition)
    
    // 计算跳过的记录数
    const skip = (page - 1) * pageSize
    
    // 获取总数
    const countResult = await db.collection('user_login_logs')
      .where(whereCondition)
      .count()
    
    const totalCount = countResult.total
    
    // 获取登录日志列表
    const logsResult = await db.collection('user_login_logs')
      .where(whereCondition)
      .orderBy('loginTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()
    
    // 处理登录日志数据
    const logs = logsResult.data.map(log => ({
      _id: log._id,
      loginTime: log.loginTime,
      loginType: log.loginType,
      clientIP: log.clientIP,
      deviceInfo: log.deviceInfo,
      locationInfo: log.locationInfo,
      sessionId: log.sessionId,
      userAgent: log.userAgent,
      source: log.source || 'unknown',
      description: log.description || '',
      // 格式化显示用的字段
      loginTimeText: formatTime(log.loginTime),
      deviceText: getDeviceText(log.deviceInfo),
      locationText: getLocationText(log.locationInfo),
      loginTypeText: getLoginTypeText(log.loginType),
      sourceText: getSourceText(log.source)
    }))
    
    // 获取登录统计信息
    const stats = await getLoginStats(OPENID)
    
    console.log(`✅ 获取到 ${logs.length} 条登录日志，总计 ${totalCount} 条`)
    
    return {
      success: true,
      data: {
        logs: logs,
        pagination: {
          page: page,
          pageSize: pageSize,
          totalCount: totalCount,
          totalPages: Math.ceil(totalCount / pageSize),
          hasMore: skip + logs.length < totalCount
        },
        stats: stats
      }
    }
    
  } catch (error) {
    console.error('❌ 获取登录日志失败:', error)
    return {
      success: false,
      error: error.message || '获取登录日志失败'
    }
  }
}

// 格式化时间
function formatTime(time) {
  if (!time) return ''
  
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取设备信息文本
function getDeviceText(deviceInfo) {
  if (!deviceInfo) return '未知设备'
  
  const parts = []
  if (deviceInfo.brand) parts.push(deviceInfo.brand)
  if (deviceInfo.model) parts.push(deviceInfo.model)
  if (deviceInfo.system) parts.push(deviceInfo.system)
  
  return parts.length > 0 ? parts.join(' ') : '未知设备'
}

// 获取位置信息文本
function getLocationText(locationInfo) {
  if (!locationInfo) return '未知位置'
  
  const parts = []
  if (locationInfo.country && locationInfo.country !== 'China') {
    parts.push(locationInfo.country)
  }
  if (locationInfo.province) parts.push(locationInfo.province)
  if (locationInfo.city) parts.push(locationInfo.city)
  
  return parts.length > 0 ? parts.join(' ') : '未知位置'
}

// 获取登录类型文本
function getLoginTypeText(loginType) {
  const typeMap = {
    'wechat': '微信登录',
    'wechat_launch': '启动登录',
    'wechat_show': '切换登录',
    'wechat_attempt': '登录尝试',
    'wechat_quick_success': '快捷登录',
    'wechat_confirm': '确认登录',
    'wechat_success': '登录成功',
    'wechat_failed': '登录失败',
    'logout': '退出登录',
    'logout_cancel': '取消退出',
    'anonymous': '匿名登录',
    'phone': '手机登录',
    'email': '邮箱登录',
    'test': '测试登录'
  }
  return typeMap[loginType] || '未知类型'
}

// 获取触发来源文本
function getSourceText(source) {
  const sourceMap = {
    'launch': '应用启动',
    'show': '应用切换',
    'manual': '手动触发',
    'test': '测试触发',
    'profile_action': '个人中心',
    'unknown': '未知来源'
  }
  return sourceMap[source] || '未知来源'
}

// 获取登录统计信息
async function getLoginStats(openid) {
  console.log('📈 获取登录统计信息')
  
  try {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const thisWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
    const thisMonth = new Date(now.getFullYear(), now.getMonth(), 1)
    
    // 今日登录次数
    const todayCount = await db.collection('user_login_logs')
      .where({
        openid: openid,
        loginTime: db.command.gte(today)
      })
      .count()
    
    // 本周登录次数
    const weekCount = await db.collection('user_login_logs')
      .where({
        openid: openid,
        loginTime: db.command.gte(thisWeek)
      })
      .count()
    
    // 本月登录次数
    const monthCount = await db.collection('user_login_logs')
      .where({
        openid: openid,
        loginTime: db.command.gte(thisMonth)
      })
      .count()
    
    // 总登录次数
    const totalCount = await db.collection('user_login_logs')
      .where({ openid: openid })
      .count()
    
    // 最后登录时间
    const lastLoginResult = await db.collection('user_login_logs')
      .where({ openid: openid })
      .orderBy('loginTime', 'desc')
      .limit(1)
      .get()
    
    const lastLoginTime = lastLoginResult.data.length > 0 
      ? lastLoginResult.data[0].loginTime 
      : null
    
    return {
      todayCount: todayCount.total,
      weekCount: weekCount.total,
      monthCount: monthCount.total,
      totalCount: totalCount.total,
      lastLoginTime: lastLoginTime,
      lastLoginTimeText: lastLoginTime ? formatTime(lastLoginTime) : '从未登录'
    }
    
  } catch (error) {
    console.error('❌ 获取登录统计失败:', error)
    return {
      todayCount: 0,
      weekCount: 0,
      monthCount: 0,
      totalCount: 0,
      lastLoginTime: null,
      lastLoginTimeText: '获取失败'
    }
  }
}
